package com.esayread.ui.bookshelf

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Book
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.CheckBoxOutlineBlank
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImage
import coil.request.ImageRequest
import androidx.navigation.NavController
import com.esayread.data.Book
import com.esayread.data.BookFormat
import com.esayread.data.ScanResultHolder
import com.esayread.utils.BookManager
import com.esayread.utils.FileScanner
import kotlinx.coroutines.launch
import java.io.File
import android.util.Log

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BookSelectionScreen(
    navController: NavController,
    onBooksSelected: (List<Book>) -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val bookManager = remember { BookManager(context) }
    val fileScanner = remember { FileScanner(context) }
    
    // 扫描状态
    var scannedBooks by remember { mutableStateOf(ScanResultHolder.getScannedBooks()) }
    var isScanning by remember { mutableStateOf(false) }
    var selectedBooks by remember { mutableStateOf(setOf<String>()) }
    var isProcessing by remember { mutableStateOf(false) }
    
    // 自动开始扫描（如果没有扫描结果）
    LaunchedEffect(Unit) {
        if (scannedBooks.isEmpty()) {
            Log.d("BookSelectionScreen", "开始自动扫描...")
            isScanning = true
            
            fileScanner.scanAllBooksLazy(
                onBookFound = { book ->
                    // 实时添加扫描到的书籍
                    scannedBooks = scannedBooks + book
                    ScanResultHolder.setScannedBooks(scannedBooks)
                    Log.d("BookSelectionScreen", "实时发现书籍: ${book.title}")
                },
                onScanComplete = { finalBooks ->
                    Log.d("BookSelectionScreen", "扫描完成，共找到 ${finalBooks.size} 本书")
                    scannedBooks = finalBooks
                    ScanResultHolder.setScannedBooks(finalBooks)
                    isScanning = false
                }
            )
        }
    }
    
    // 格式筛选状态
    var selectedFormat by remember { mutableStateOf<BookFormat?>(null) }
    
    // 根据选择的格式筛选书籍
    val filteredBooks = remember(scannedBooks, selectedFormat) {
        if (selectedFormat == null) {
            scannedBooks
        } else {
            scannedBooks.filter { it.format == selectedFormat }
        }
    }
    
    // 获取所有可用的格式
    val availableFormats = remember(scannedBooks) {
        scannedBooks.map { it.format }.distinct().sorted()
    }
    
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部栏
        TopAppBar(
            title = { 
                Text(
                    text = if (isScanning) {
                        "正在扫描... (已找到${scannedBooks.size}本)"
                    } else {
                        "选择要添加的书籍 (${filteredBooks.size}本${if (selectedFormat != null) "/共${scannedBooks.size}本" else ""})"
                    },
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Medium
                )
            },
            navigationIcon = {
                IconButton(onClick = { navController.popBackStack() }) {
                    Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = "返回"
                    )
                }
            },
            actions = {
                // 全选/取消全选
                TextButton(
                    onClick = {
                        val filteredBookIds = filteredBooks.map { it.id }.toSet()
                        selectedBooks = if (selectedBooks.containsAll(filteredBookIds)) {
                            selectedBooks - filteredBookIds
                        } else {
                            selectedBooks + filteredBookIds
                        }
                    }
                ) {
                    val filteredBookIds = filteredBooks.map { it.id }.toSet()
                    Text(
                        text = if (selectedBooks.containsAll(filteredBookIds)) "取消全选" else "全选",
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }
        )
        
        // 格式筛选器
        if (availableFormats.isNotEmpty()) {
            LazyRow(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 全部格式选项
                item {
                    FilterChip(
                        onClick = { selectedFormat = null },
                        label = { Text("全部 (${scannedBooks.size})") },
                        selected = selectedFormat == null
                    )
                }
                
                // 各个格式选项
                items(availableFormats.size) { index ->
                    val format = availableFormats[index]
                    val count = scannedBooks.count { it.format == format }
                    FilterChip(
                        onClick = { selectedFormat = format },
                        label = { Text("${format.name} ($count)") },
                        selected = selectedFormat == format
                    )
                }
            }
        }
        
        // 书籍列表或空状态
        if (scannedBooks.isEmpty()) {
            // 空状态或扫描中状态
            Column(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .padding(32.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                if (isScanning) {
                    // 扫描中状态
                    CircularProgressIndicator(
                        modifier = Modifier.size(64.dp),
                        strokeWidth = 4.dp
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "正在扫描设备中的电子书...",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "请稍候，正在搜索所有支持的电子书格式",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                } else {
                    // 扫描完成但未找到书籍
                    Icon(
                        imageVector = Icons.Default.Book,
                        contentDescription = null,
                        modifier = Modifier.size(64.dp),
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "未找到电子书文件",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "扫描完成，但未找到新的电子书文件。\n\n可能的原因：\n• 设备中没有支持的电子书文件\n• 权限未正确授予\n• 文件格式不受支持\n\n支持的格式：EPUB、PDF、MOBI、TXT、DOC、DOCX\n扫描范围：整个外部存储的所有目录",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = androidx.compose.ui.text.style.TextAlign.Center
                    )
                }
            }
        } else {
            // 书籍列表
            LazyColumn(
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(filteredBooks) { book ->
                    BookSelectionItem(
                        book = book,
                        isSelected = selectedBooks.contains(book.id),
                        onSelectionChanged = { isSelected: Boolean ->
                            selectedBooks = if (isSelected) {
                                selectedBooks + book.id
                            } else {
                                selectedBooks - book.id
                            }
                        }
                    )
                }
            }
        }
        
        // 底部按钮
        Surface(
            modifier = Modifier.fillMaxWidth(),
            shadowElevation = 8.dp
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                OutlinedButton(
                    onClick = { navController.popBackStack() },
                    enabled = !isProcessing,
                    modifier = Modifier.weight(1f)
                ) {
                    Text("取消")
                }
                
                Spacer(modifier = Modifier.width(16.dp))
                
                Button(
                    onClick = {
                        if (selectedBooks.isNotEmpty()) {
                            isProcessing = true
                            coroutineScope.launch {
                                try {
                                    val selected = scannedBooks.filter { selectedBooks.contains(it.id) }
                                    val copiedBooks = bookManager.copyBooksToLibrary(selected)
                                    onBooksSelected(copiedBooks)
                                    // 清除扫描结果
                                    ScanResultHolder.clearScannedBooks()
                                    // 处理完成后重置状态
                                    isProcessing = false
                                    // 返回书架页面（书架页面会自动刷新）
                                    navController.popBackStack()
                                } catch (e: Exception) {
                                    Log.e("BookSelectionScreen", "Error adding books to library", e)
                                    isProcessing = false
                                    // TODO: 显示错误信息给用户
                                }
                            }
                        }
                    },
                    enabled = selectedBooks.isNotEmpty() && !isProcessing,
                    modifier = Modifier.weight(1f)
                ) {
                    if (isProcessing) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            strokeWidth = 2.dp
                        )
                    } else {
                        Text("添加 (${selectedBooks.size})")
                    }
                }
            }
        }
    }
}

@Composable
fun BookSelectionItem(
    book: Book,
    isSelected: Boolean,
    onSelectionChanged: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { onSelectionChanged(!isSelected) },
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 选择框
            Icon(
                imageVector = if (isSelected) Icons.Default.CheckBox else Icons.Default.CheckBoxOutlineBlank,
                contentDescription = if (isSelected) "已选择" else "未选择",
                tint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(24.dp)
            )
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 书籍封面
            Box(
                modifier = Modifier
                    .size(60.dp, 80.dp)
                    .clip(RoundedCornerShape(4.dp))
                    .background(MaterialTheme.colorScheme.surfaceVariant),
                contentAlignment = Alignment.Center
            ) {
                if (book.coverPath != null && java.io.File(book.coverPath).exists()) {
                    AsyncImage(
                        model = ImageRequest.Builder(LocalContext.current)
                            .data(book.coverPath)
                            .crossfade(true)
                            .build(),
                        contentDescription = "书籍封面",
                        modifier = Modifier.fillMaxSize(),
                        contentScale = ContentScale.Crop
                    )
                } else {
                    Icon(
                        imageVector = Icons.Default.Book,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(32.dp)
                    )
                }
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 书籍信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = book.title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                    color = MaterialTheme.colorScheme.onSurface
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = book.author,
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = book.format.name,
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.primary,
                        modifier = Modifier
                            .background(
                                MaterialTheme.colorScheme.primaryContainer,
                                RoundedCornerShape(4.dp)
                            )
                            .padding(horizontal = 6.dp, vertical = 2.dp)
                    )
                    
                    Spacer(modifier = Modifier.width(8.dp))
                    
                    Text(
                        text = getReadableFileSize(File(book.filePath).length()),
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                Spacer(modifier = Modifier.height(2.dp))
                
                Text(
                    text = book.filePath,
                    fontSize = 11.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}

fun getReadableFileSize(size: Long): String {
    val units = arrayOf("B", "KB", "MB", "GB")
    var fileSize = size.toDouble()
    var unitIndex = 0
    
    while (fileSize >= 1024 && unitIndex < units.size - 1) {
        fileSize /= 1024
        unitIndex++
    }
    
    return String.format("%.1f %s", fileSize, units[unitIndex])
}